package com.xiguaji.tiktok.task.aweme.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.tiktok.task.aweme.Aweme;
import com.xiguaji.tiktok.task.aweme.repository.AwemeRepository;
import com.xiguaji.tiktok.task.aweme.spider.model.Aweme_list;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 爬虫保存推荐流数据
 */
@Component
public class SaveAwemeEventListener implements IEventListener<SaveAwemeEventListener.SaveAwemeEvent> {

    @Autowired
    AwemeRepository awemeRepository;

    @Autowired
    Aweme.AwemeMapper awemeMapper;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SaveAwemeEvent event) {
        if (CollectionUtils.isEmpty(event.aweme_lists)) {
            return;
        }
        var awemeEntities = awemeMapper.mapper(event.aweme_lists);
        awemeRepository.insertOrUpdate(awemeEntities, event.getSource());
    }

    public static class SaveAwemeEvent extends Event {
        public SaveAwemeEvent(Event event, List<Aweme_list> aweme_lists) {
            super(event, "SaveAweme");
            this.aweme_lists = aweme_lists;
        }

        public SaveAwemeEvent(List<Aweme_list> aweme_lists) {
            this(null, aweme_lists);
        }

        private List<Aweme_list> aweme_lists;
    }
}